package com.wms.common.util;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import com.wms.execcmd.CommandWrapper;
import com.wms.execcmd.DefaultOutputReader;



public class CommonTools {
	static Logger logger =  Logger.getLogger(CommonTools.class);
	public static String runCmd(String cmd) throws Exception{
		DefaultOutputReader stdoutReader = new DefaultOutputReader(logger);
		DefaultOutputReader stderrReader = new DefaultOutputReader(logger);
		String stdout,stderr;
		CommandWrapper cmdwrapper = new CommandWrapper(logger);
		cmdwrapper.setStdoutReader(stdoutReader);
		cmdwrapper.setStderrReader(stderrReader);
		cmdwrapper.exec(cmd.split(" "), null);
		stdout = stdoutReader.getBuffer().toString();
		stderr = stderrReader.getBuffer().toString();
		if(null!=stderr && !"".equals(stderr)){
			logger.warn(stderr);
		}
		if(null==stdout || "".equals(stdout)){
			logger.warn("no output from command:"+cmd);
		}
		return stdout;
	}	
	
	public static boolean fPingTest(String ip) throws Exception{
		String fpingPath = System.getenv("CI_TOP") + File.separator + System.getenv("GUI_VERSION") + File.separator + "etc" +File.separator + "fping";
		String cmd = fpingPath + " -r 1 " +ip;
		String result = runCmd(cmd);
		if(result.contains("is alive")){
			return true;
		}
		return false;
	}
	
	public static Date getMondayDate(Date date) throws Exception{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int weekdate = calendar.get(Calendar.DAY_OF_WEEK);
		calendar.add(Calendar.DATE, -(weekdate-2));
		return calendar.getTime();
	}
	
	public static void main(String[] args) throws Exception{
		Date d = CommonTools.getMondayDate(new Date());
		System.out.println(d);
	}
}
